package net.cn_su.sharpeyes.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import net.cn_su.sharpeyes.R;
import net.cn_su.sharpeyes.application.SuApplication;
import net.cn_su.sharpeyes.beans.Organization;
import net.cn_su.sharpeyes.pref.ServerInfo_;
import net.cn_su.sharpeyes.update.AppUpdateUtil;
import net.cn_su.sharpeyes.update.UpdateCallBack;
import net.cn_su.sharpeyes.utils.UIUtil;
import net.cn_su.sharpeyes.utils.http.HttpClient;
import net.cn_su.sharpeyes.utils.http.HttpUrl;
import net.cn_su.sharpeyes.utils.http.JacksonMapper;
import net.cn_su.sharpeyes.view.gif.GifView;
import net.cn_su.sharpeyes.view.other.ClearEditText;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 登录
 */
@EActivity(R.layout.activity_login)
@Fullscreen
public class LoginActivity extends AppCompatActivity {

    @ViewById(R.id.gif)
    GifView mGifView;
    @ViewById
    LinearLayout ll_loading, ll_login;

    @ViewById
    ClearEditText et_acount, et_pwd, et_url;

    @App
    protected SuApplication suApplication;
    @Pref
    protected ServerInfo_ serverInfo;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @AfterViews
    protected void initData() {
        if (!serverInfo.localAccount().get().equals("-1")) {
            et_acount.setText(serverInfo.localAccount().get());
            et_pwd.setText(serverInfo.localPassword().get());
        }

        et_url.setText(serverInfo.serverUrl().get());

        //检查更新
        RequestParams params = new RequestParams();
        params.put("type", "1");
        new AppUpdateUtil(this, params).checkUpdate(new UpdateCallBack() {
            @Override
            public void onError() {

            }

            @Override
            public void isUpdate(String result) {

            }

            @Override
            public void isNoUpdate() {

            //    Logger.v("isNoUpdate");
            }
        });


    }

    //注册
    @Click(R.id.tv_regist)
    protected void registBtnClick() {
        //判断是否填写域名

        if (et_url.getText().toString().equals("")) {
            et_url.requestFocus();
            UIUtil.showToast(this, "请输入请求域名");
            return;
        }

        serverInfo.serverUrl().put(et_url.getText().toString());
        HttpUrl.setROOT(et_url.getText().toString()+"/api/");

        RegistActivity_.intent(LoginActivity.this).startForResult(1);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mGifView != null)
            mGifView.pause();

    }

    @Click(R.id.tv_confirm)
    protected void confirmBtnClick() {

        if (et_url.getText().toString().equals("")) {
            et_url.requestFocus();
            UIUtil.showToast(this, "请输入请求域名");
            return;
        }


        if (et_acount.getText().toString().length() == 0) {
            et_acount.requestFocus();
            UIUtil.showToast(this, "请输入账号");
            return;
        }
        if (et_pwd.getText().toString().length() == 0) {
            et_pwd.requestFocus();
            UIUtil.showToast(this, "请输入密码");
            return;
        }

        serverInfo.serverUrl().put(et_url.getText().toString());

        HttpUrl.setROOT(et_url.getText().toString()+"/api/");


        showLoading();
        loginServer();


    }

    /**
     * 登录自有平台
     */
    private void loginServer() {

        RequestParams params = new RequestParams();
        params.add("login", et_acount.getText().toString());
        params.add("password", et_pwd.getText().toString());
        HttpClient.post(LoginActivity.this, HttpUrl.LOGIN, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
           //     Logger.v("response==" + response);
                // 保存登录信息
                try {
                    JSONObject server = response.getJSONObject("server");
                    serverInfo.serverAddress().put(server.getString("url"));
                    serverInfo.hikAccount().put(server.getString("account"));
                    serverInfo.hikPassword().put(server.getString("password"));

                    serverInfo.userId().put(response.getInt("id"));

                    //记录账号信息
                    serverInfo.localAccount().put(et_acount.getText().toString());
                    serverInfo.localPassword().put(et_pwd.getText().toString());
                    serverInfo.userName().put(response.getString("name"));
                    serverInfo.isLogin().put(true);

                    //判断是否有申请通过的列表
                    getApplyList();


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {

                hideLoading();
                UIUtil.showToast(LoginActivity.this, R.string.login_server_failed);
                try {
      //              Logger.d(errorResponse.getString("error_description"));
                } catch (Exception e) {

                }

                //  showLoading();
            }
        });
    }

    @UiThread
    protected void showLoading() {
        mGifView.play();
        ll_loading.setVisibility(View.VISIBLE);
        ll_login.setVisibility(View.GONE);
    }

    @UiThread
    protected void hideLoading() {
        ll_loading.setVisibility(View.GONE);
        ll_login.setVisibility(View.VISIBLE);
        mGifView.pause();
    }

    private void getApplyList() {

        RequestParams params = new RequestParams();
        params.add("user_id", serverInfo.userId().get().toString());

        HttpClient.get(HttpUrl.GET_ORG_APPLY, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                OrgChooseActivity_.intent(LoginActivity.this).extra("flag", true).start();
                finish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

          //      Logger.v("result==" + responseString);
                List<Organization> organizationList = JacksonMapper.parseToList(responseString, new TypeReference<List<Organization>>() {
                });


                //已申请通过的列表
                List<Organization> mApplyList = getApplyOrganizations(organizationList);

                if (mApplyList.size() == 0) {
                    OrgChooseActivity_.intent(LoginActivity.this).extra("flag", true).start();
                    finish();
                } else {
                    Organization org = mApplyList.get(0);
                    LiveActivity_.intent(LoginActivity.this).extra("orgId", org != null ? org.getId() : -1).start();
                    finish();
                }


            }
        });


    }


    /**
     * 得到申请通过的列表
     *
     * @param orgs
     * @return
     */
    public List<Organization> getApplyOrganizations(List<Organization> orgs) {
        List<Organization> organizations = new ArrayList<>();
        // 将镇进行一次处理, 作为村的点来处理
        List<Organization> children = null;
        for (Organization org : orgs) {
            if (org.getChildren() != null && org.getChildren().size() > 0) {
                children = new ArrayList<>();
                for (Organization val : org.getChildren()) {
                    if (val.getStatus() == 1) {
                        children.add(val);
                    }
                }
                organizations.addAll(children);
            }
        }
        suApplication.setOrganizations(organizations);
        return organizations;
    }
}
